//
//  QualificationCertificationViewController.m
//  WHB_logist
//
//  Created by 徐国庆 on 15/12/7.
//  Copyright (c) 2015年 turing. All rights reserved.
//

#import "QualificationCertificationViewController.h"
#import <CoreMedia/CMFormatDescription.h>
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>
#import "CTAssetsPickerController.h"
#import "VPImageCropperViewController.h"
#import "HttpHelper.h"
#import <MBProgressHUD.h>
#import "UIAdapterHelper.h"

@interface QualificationCertificationViewController ()<UITableViewDataSource, UITableViewDelegate,UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, CTAssetsPickerControllerDelegate, VPImageCropperDelegate, UIAlertViewDelegate>

@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSArray *array;

// 上传图片使用
@property(nonatomic, strong) UIImagePickerController* pickerCamera;
@property(nonatomic, strong) CTAssetsPickerController *ctapicker;
@property(nonatomic, strong) NSString *imageName;//上传图片名称

@end

@implementation QualificationCertificationViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.array = [NSArray arrayWithObjects:@"企业名称", @"营业执照副本", @"危险品经营许可证", @"组织机构代码", @"税证登记证", nil];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navtitle.text = @"资质认证";
    [self initWithView];
    
}

#pragma mark UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *indentifer = @"qualificationCertificationCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:indentifer];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifer];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    cell.textLabel.text = [self.array objectAtIndex:indexPath.row];
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    
    if (indexPath.row < self.array.count - 1) {
        UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(-1, 44, kUIScreenWidth + 2, 10)];
        lineLabel.layer.borderWidth = 0.5;
        lineLabel.backgroundColor = [UIColor HexStrWithColor:@"F0F0F0"];
        lineLabel.layer.borderColor = [UIColor HexStrWithColor:@"d0d0d0"].CGColor;
        [cell.contentView addSubview:lineLabel];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == self.array.count - 1) {
        return 44;
    }
    return 54;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"资质认证");
    if (indexPath.row == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"昵称修改" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"修改",nil];
        [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
        [alert show];
    } else{
        [self choosePhoto];
    }
}

#pragma mark UIAlertView代理 修改昵称
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    UITextField *tf = [alertView textFieldAtIndex:0];
    if (buttonIndex == 1) {
        NSLog(@"修改%@", tf.text);
    } else{
        NSLog(@"取消");
    }
}

#pragma mark 提交审核
- (void)footerButtonAction:(UIButton *)button{
    NSLog(@"提交审核");
}

#pragma mark 选择拍照或相册图片
- (void)choosePhoto{
    UIActionSheet *SheetMenu = [[UIActionSheet alloc] initWithTitle:@"请选择"
                                                           delegate:self
                                                  cancelButtonTitle:@"取消"
                                             destructiveButtonTitle:nil
                                                  otherButtonTitles:@"摄像头拍照",@"从相册选择", nil];
    [SheetMenu showInView:self.view];
}

#pragma mark ActionSheetDelegate
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *title = [actionSheet buttonTitleAtIndex:buttonIndex];
    
    if ([title isEqualToString:@"摄像头拍照"]){
        if (_pickerCamera == nil){
            _pickerCamera = [[UIImagePickerController alloc] init];
            _pickerCamera.sourceType = UIImagePickerControllerSourceTypeCamera;
            [_pickerCamera setCameraCaptureMode:UIImagePickerControllerCameraCaptureModePhoto];
            _pickerCamera.delegate = self;
        }
        [self presentViewController:_pickerCamera animated:YES completion:^{
            if (IsIOS7) {
                AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
                if (authStatus != AVAuthorizationStatusAuthorized){
                    PXAlertView *alertview = [PXAlertView showAlertWithTitle:@"系统提示" message:@"请打开设置隐私相机允许访问" cancelTitle:@"确 认" completion:nil];
                    [alertview useDefaultIOS7Style];
                    return;
                }
            }
        }];
    }
    else if([title isEqualToString:@"从相册选择"]){
        UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
        [self selectPhoto:btn];
    }
}


//选择照片
-(void)selectPhoto:(id)sender
{
    _ctapicker=[[CTAssetsPickerController alloc]init];
    _ctapicker.delegate=self;
    _ctapicker.showsNumberOfAssets=YES;
    _ctapicker.assetsFilter=[ALAssetsFilter allPhotos];
    
    UIImageView *navbar = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kUIScreenWidth, kNavHeight)];
    navbar.image = [UIImage imageNamed:@"jian"];
    navbar.image = [navbar.image resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0) resizingMode:UIImageResizingModeStretch];
    [_ctapicker.navigationController.navigationBar setBackgroundImage:navbar.image forBarMetrics:UIBarMetricsDefault];
    [_ctapicker.childNavigationController.navigationBar setBackgroundImage:navbar.image forBarMetrics:UIBarMetricsDefault];
    //设置左右按钮文字颜色
    _ctapicker.childNavigationController.navigationBar.tintColor = [UIColor whiteColor];
    //设置标题文字颜色
    _ctapicker.childNavigationController.navigationBar.titleTextAttributes=[NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
    [self.navigationController presentViewController:_ctapicker animated:YES completion:nil];
}


#pragma mark - CTAssetsPickerControllerDelegate  选图片代理
- (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    UIImage *newImage;
    for (ALAsset *ass in assets) {
        
        ALAssetRepresentation *representation = ass.defaultRepresentation;
        UIImage *originImage =[UIImage imageWithCGImage:representation.fullResolutionImage scale:representation.scale orientation:(UIImageOrientation)representation.orientation];
        CGFloat width = 900;
        CGFloat height = originImage.size.height/originImage.size.width * width;
        //压缩后新图
        newImage=[UtilsHelper imageWithImageSize:originImage scaledToSize:CGSizeMake(width, height)];
    }
    [picker dismissViewControllerAnimated:YES completion:^{
        [self openCropper:newImage];
    }];
}

#pragma mark 设置最多允许选择的数量
-(BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(ALAsset *)asset
{
    return picker.selectedAssets.count < 1;
}

#pragma mark ImagePickerDelegate 拍照后调用
-(void)imagePickerController:(UIImagePickerController *)pickerMy didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:@"public.image"])
    {
        UIImage *originImage = [info objectForKey:UIImagePickerControllerOriginalImage];
        CGFloat width = 900;
        CGFloat height = originImage.size.height/originImage.size.width * width;
        //压缩后新图
        UIImage *newImage=[UtilsHelper imageWithImageSize:originImage scaledToSize:CGSizeMake(width, height)];
        [pickerMy dismissViewControllerAnimated:YES completion:^{
            [self openCropper:newImage];
        }];
    }
}

#pragma mark OSS上传图片
-(void)osstest:(UIImage*)image
{
    //生成图片名称
    _imageName = [NSString stringWithFormat:@"headImg/%@.png",kIdentifierString];
    // 上传
    
    [HttpHelper ossuploadimage:image fullimageName:_imageName uploadCallback:^(BOOL isSuccess, NSError *error) {
        
        if (isSuccess) {
            dispatch_async(dispatch_get_main_queue(), ^{
                
                NSLog(@"上传成功");
                //                [SVProgressHUD setBackgroundColor:RGBA(0, 0, 0, 0.8)];
                //                [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
                //                [SVProgressHUD showSuccessWithStatus:@"上传成功"];
                
                //设置头像
                NSString *fullImageName = [NSString stringWithFormat:@"%@%@%@",aliyunOSSIMGURL,_imageName,[UIAdapterHelper returnHeadImageSize]];
//                [self.changeButton sd_setImageWithURL:[NSURL URLWithString:fullImageName] forState:UIControlStateNormal];
                //                [_btnPhoto sd_setImageWithURL:[NSURL URLWithString:fullImageName] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"Headshop"]];
                //                //设置模糊背景
                //                [_headerbackground sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", fullImageName, @"_30-30bl_-25b"]] placeholderImage:[UIImage imageNamed:@"bg"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                //                }];
            });
            
        }else{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                //                [SVProgressHUD setBackgroundColor:RGBA(0, 0, 0, 0.8)];
                //                [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
                //                [SVProgressHUD showErrorWithStatus:@"上传失败，请重新上传"];
                NSLog(@"上传失败");
            });
        }
        
    } withProgressCallback:^(float progressFloat) {
        //        [SVProgressHUD showProgress:progressFloat status:@"正在上传"];
        NSLog(@"正在上传");
    }];
    
}

#pragma mark 图片裁切
-(void)openCropper:(UIImage*)selsectImg{
    
    VPImageCropperViewController *imgCropper = [[VPImageCropperViewController alloc] initWithImage:selsectImg cropFrame:CGRectMake(0, 100.0f, kUIScreenWidth, kUIScreenWidth) limitScaleRatio:3.0];
    imgCropper.delegate = self;
    [self presentViewController:imgCropper animated:YES completion:nil];
}

#pragma mark VPImageCropperDelegate
- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    
    //裁切图片后上传
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
        [self osstest:editedImage];
    }];
}

- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController{
    [cropperViewController dismissViewControllerAnimated:YES completion:nil];
}

- (void)commitButtonAction:(UIButton *)button{
    
}


#pragma mark 初始化视图
- (void)initWithView{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kUIScreenWidth, kUIScreenHeight) style:UITableViewStyleGrouped];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.tableFooterView = [self footerView];
    self.tableView.tableHeaderView = [self headerView];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.scrollEnabled = NO;
    [self.view addSubview:self.tableView];
}

#pragma mark 头
- (UIView *)headerView{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, kNavHeight, kUIScreenWidth, 40)];
    
    UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kUIScreenWidth + 2, 40)];
    lineLabel.backgroundColor = [UIColor HexStrWithColor:@"FF8000"];
    lineLabel.text = @"审核状态:审核中，预计两个工作日完成";
    lineLabel.font = [UIFont systemFontOfSize:14];
    lineLabel.textColor = [UIColor whiteColor];
    lineLabel.textAlignment = 1;
    
    [view addSubview:lineLabel];
    
    return view;
}

#pragma mark 脚
- (UIView *)footerView{
    
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kUIScreenWidth, 40)];
    
    UIButton *footerButton = [UIButton buttonWithType:UIButtonTypeCustom];
    footerButton.frame = CGRectMake(10, 0, kUIScreenWidth - 20, 40);
    footerButton.layer.masksToBounds = YES;
    footerButton.layer.cornerRadius = 5;
    [footerButton setTitle:@"提交审核" forState:UIControlStateNormal];
    footerButton.backgroundColor = [UIColor HexStrWithColor:@"CE0000"];
    [footerButton addTarget:self action:@selector(footerButtonAction:) forControlEvents:UIControlEventTouchDown];
    [bottomView addSubview:footerButton];
    return bottomView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
